from project.models import ProjectCodeRepository, Project
from pms.common.utils import flatten_view


def repository_view(repository):
    assert isinstance(repository, ProjectCodeRepository)
    return {
        'id': repository.id,
        'name': repository.name,
        'href': repository.href,
        'pid': repository.pid.id
    }


def project_add_repository(project, name, href):
    assert isinstance(project, Project)
    new_repository = ProjectCodeRepository(name=name, href=href, pid=project)
    new_repository.save()
    return new_repository


def update_repository(repository, view):
    assert isinstance(repository, ProjectCodeRepository)
    argv = flatten_view(view, {
        'name': 'name',
        'href': 'href'
    })
    repository.__dict__.update(**argv)
    repository.save()
    return repository
